package cen5501c.utilities;

import java.io.File;

public class FileFraction implements Comparable<FileFraction> {
	private String fileName = null;
	private String hash = null;
	private int start = 0;
	private int end = 0;
	private File file = null;
	private static String ending = "_end";
	private boolean isComplete = false;
	private boolean fileEnd = false;

	public boolean isComplete() {
		return isComplete;
	}

	public File getFile() {
		return file;
	}

	public boolean checkComplete() {
		isComplete = (start == 0 && fileName.indexOf(ending) != -1);
		return isComplete;
	}

	public boolean validate() {
		if (!isComplete)
			return false;
		else {
			// to be implemented
			return false;
		}
	}

	public boolean isFileEnd() {
		return fileEnd;
	}

	public void setFileEnd(boolean fileEnd) {
		this.fileEnd = fileEnd;
	}

	public FileFraction(File file) throws Exception {
		this.file = file;
		String fileName = file.getName();
		this.fileName = fileName;
		int hashStart=fileName.indexOf("[")+1;
		while(fileName.charAt(hashStart+32)!=']'){
			hashStart=fileName.indexOf("[",hashStart);
		}
//		hash = fileName.substring(fileName.indexOf(".txt[") + 5, fileName
//				.indexOf("]_"));
		hash=fileName.substring(hashStart, hashStart+32);
		start = Integer.parseInt(fileName.substring(fileName.indexOf("]_") + 2,
				fileName.indexOf("_", fileName.indexOf("]_") + 2)));
		try {
			end = Integer.parseInt(fileName.substring(fileName.indexOf("_",
					fileName.indexOf("]_") + 2) + 1));
		} catch (NumberFormatException nfe) {
			end = Integer.parseInt(fileName.substring(fileName.indexOf("_",
					fileName.indexOf("]_") + 2) + 1, fileName.indexOf(ending)));
			fileEnd = true;
		}
		checkComplete();
	}

	public int compareTo(FileFraction o) {
		if (this.start < o.start)
			return -1;
		if (this.start < o.start)
			return 0;
		else
			return 1;
	}

	public int getEnd() {
		return end;
	}

	public String getFileName() {
		return fileName;
	}

	public String getHash() {
		return hash;
	}

	public int getStart() {
		return start;
	}

	public static void main(String args[]) {
		// // FileFraction ff=new FileFraction("a.txt[MD5hash]_2_10");
		// System.out.println(ff.getFileName());
		// System.out.println(ff.getHash());
		// System.out.println(ff.getStart());
		// System.out.println(ff.getEnd());
	}

	public void setEnd(int end) {
		this.end = end;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
